<template>
  <view>
    <view class="profile-container" :class="{ 'mobile': isMobile }">
        <!-- 背景装饰 -->
        <view class="background-overlay"></view>
        
        <!-- 顶部设置按钮 -->
        <view class="settings-header">
            <button class="settings-btn" @click="goToSettings">
                <i class="fas fa-cog"></i>
                <text class="settings-text">设置</text>
            </button>
        </view>
        
        <view class="profile-card slide-in-up">
            <view class="card-header">
                <view class="avatar-wrapper" @click="goToAvatarEditor">
                    <image :src="getAvatarUrl(userInfo.avatar)" class="avatar-canvas" />
                </view>
                <view class="user-identity">
                    <text class="username">{{ userInfo.name }}</text>
                    <text class="role-tag" :class="userInfo.role">
                        <i class="fas" :class="userInfo.role === 'admin' ? 'fa-user-shield' : 'fa-user'"></i>
                        {{ userInfo.role === 'admin' ? '管理员' : '普通用户' }}
                    </text>
                </view>
            </view>
            <view class="card-body">
                <view class="info-item">
                    <i class="info-icon fas fa-envelope"></i>
                    <text class="label">邮箱:</text>
                    <text class="value">{{ userInfo.email }}</text>
                </view>
                <view class="info-item">
                    <i class="info-icon fas fa-layer-group"></i>
                    <text class="label">等级:</text>
                    <text class="value">Lv.{{ userInfo.level || 1 }}</text>
                </view>
                <view class="info-item">
                    <i class="info-icon fas fa-coins"></i>
                    <text class="label">积分:</text>
                    <text class="value">{{ userInfo.points || 0 }}</text>
                </view>
                <view class="info-item">
                    <i class="info-icon fas fa-calendar-alt"></i>
                    <text class="label">注册时间:</text>
                    <text class="value">{{ formatTime(userInfo.created_at) }}</text>
                </view>
            </view>
            <view class="card-footer">
                <button class="footer-btn posts-btn" @click="goToMyPosts">
                    <i class="fas fa-rocket"></i> 我的动态
                </button>

                <button class="footer-btn points-history-btn" @click="goToPointsHistory">
                    <i class="fas fa-history"></i> 积分历史
                </button>
                <button class="footer-btn points-ranking-btn" @click="goToPointsRanking">
                    <i class="fas fa-trophy"></i> 积分排行
                </button>
                <button class="footer-btn html-games-btn" @click="goToHtmlGames">
                    <i class="fas fa-gamepad"></i> HTML游戏
                </button>
            </view>
        </view>
    </view>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/user';

import { generateAvatarSvg } from '@/utils/avatar';
import { handleApiError } from '@/utils/error-handler';

import { useUserStore } from '@/stores/user';
import { 
  initializeUserStore, 
  getCurrentUserId, 
  isUserLoggedIn,
  updateUserPoints 
} from '@/utils/auth';
import { validateBeforeOperation } from '@/utils/auth';
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';

export default {
    components: {
        UniPopup
    },
    data() {
        return {
            userInfo: {
                name: '',
                email: '',
                level: 1,
                points: 0,
                role: 'user',
                avatar: null,
                created_at: ''
            },
            isMobile: false,
        };
    },
    onLoad() {
        const systemInfo = uni.getSystemInfoSync();
        this.isMobile = systemInfo.windowWidth < 768;
        this.isTablet = systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 1024;
        this.isDesktop = systemInfo.windowWidth >= 1024;
        
        // 初始化用户store
        initializeUserStore();
        
        // 检查登录状态
        if (!isUserLoggedIn()) {
            console.log('用户未登录，跳转到登录页面');
            uni.reLaunch({ url: '/pages/login/login' });
            return;
        }
        
        const userStore = useUserStore();
        console.log('Profile页面 - Pinia store状态:', userStore.$state);
        
        // 从Pinia状态同步用户信息
        if (userStore.userId && userStore.userName) {
            this.userInfo = {
                ...this.userInfo,
                name: userStore.userName,
                email: userStore.email || '',
                level: userStore.level || 1,
                points: userStore.points || 0,
                role: userStore.role || 'user',
                avatar: userStore.avatar || null
            };
            console.log('Profile页面 - 从Pinia同步用户信息:', this.userInfo);
        }
        
        this.fetchProfile();
    },
    methods: {
        getAvatarUrl(config) {
            return generateAvatarSvg(config);
        },
        async fetchProfile() {
            try {
                const userId = getCurrentUserId(true); // 需要登录验证
                if (!userId) {
                    console.log('未找到用户ID，跳转到登录页面');
                    uni.reLaunch({ url: '/pages/login/login' });
                    return;
                }
                
                const data = await getUserInfo(userId);
                console.log('Profile页面 - API返回的用户数据:', data);
                
                // 修复字段名映射
                this.userInfo = {
                    ...this.userInfo,
                    ...data,
                    name: data.name || data.userName || data.username || this.userInfo.name, // 确保name字段正确
                    userName: data.userName || data.name || data.username,
                    email: data.email || this.userInfo.email,
                    level: data.level || this.userInfo.level,
                    points: data.points || this.userInfo.points,
                    role: data.role || this.userInfo.role,
                    avatar: data.avatar || this.userInfo.avatar
                };
                
                console.log('Profile页面 - 更新后的用户信息:', this.userInfo);
                
                // 更新用户信息到统一存储
                const userStore = useUserStore();
                userStore.setUserInfo({
                    userId: userId,
                    userName: this.userInfo.name,
                    email: this.userInfo.email,
                    level: this.userInfo.level,
                    points: this.userInfo.points,
                    role: this.userInfo.role,
                    avatar: this.userInfo.avatar,
                    token: userStore.token // 保持原有token
                });
                
                console.log('Profile页面 - 已更新Pinia store');
            } catch (error) {
                handleApiError(error, '获取用户信息');
            }
        },
        formatTime(timestamp) {
            if (!timestamp) return '未知时间';
            // 处理字符串类型的数字时间戳
            if (typeof timestamp === 'string' && !isNaN(timestamp)) {
                timestamp = Number(timestamp);
            }
            // 处理数字类型时间戳（秒级转毫秒）
            if (typeof timestamp === 'number') {
                // 检测是否为秒级时间戳（10位数字）
                if (timestamp.toString().length === 10) {
                    timestamp *= 1000;
                }
            }
            // 尝试直接解析时间戳，兼容更多格式
            let date = new Date(timestamp);
            if (isNaN(date.getTime())) {
                // 如果直接解析失败，尝试处理字符串格式
                timestamp = timestamp.replace(/-/g, '/').replace(' +0000 UTC', '');
              let date = new Date(timestamp);
                if (isNaN(date.getTime())) return '未知时间';
            }
            
            const now = new Date();
            const diff = now.getTime() - date.getTime();
            
            if (diff < 60000) return '刚刚';
            if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
            if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
            
            const year = date.getFullYear();
            const month = ('0' + (date.getMonth() + 1)).slice(-2);
            const day = ('0' + date.getDate()).slice(-2);
            return `${year}/${month}/${day} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}`;
        },
        goToAvatarEditor() {
            uni.navigateTo({ url: '/pages/avatar/avatar' });
        },
        goToMyPosts() {
            uni.navigateTo({ url: '/pages/my-posts/my-posts' });
        },

        goToPointsHistory() {
            uni.navigateTo({ url: '/pages/points/history' });
        },
        goToPointsRanking() {
            uni.navigateTo({ url: '/pages/points/ranking' });
        },

        goToSettings() {
            uni.navigateTo({ url: '/pages/settings/settings' });
        },
        goToHtmlGames() {
            uni.navigateTo({ url: '/pages/html-games/index' });
        }
    }
};
</script>

<style scoped src="./profile.css"></style>